package com.micro.service.common.base;

import com.micro.service.common.enums.DatePatternEnum;
import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
import org.slf4j.LoggerFactory;

import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;

/**
 * @author lvxiucai
 * @description
 * @date 2019/7/11
 */
public class DateTool {

    private static final org.slf4j.Logger Logger = LoggerFactory.getLogger(DateTool.class);

    public static final Date str2date(final String dateStr, final DatePatternEnum pattern) {
        Date date = null;
        try {
            DateTimeFormatter dtFormatter = DateTimeFormat.forPattern(pattern.getPattern());
            date = dtFormatter.parseDateTime(dateStr).toDate();
        } catch (Exception ex) {
            Logger.error(ex.getMessage(), ex);
        }
        return date;
    }

    public static final Date now() {
        return new DateTime().toDate();
    }

    public static final String date2str(final Date date, final DatePatternEnum pattern) {
        return new DateTime(date).toString(pattern.getPattern());
    }

    public static final String formatDate(final Date date, final DatePatternEnum pattern) {
        return new DateTime(date).toString(pattern.getPattern());
    }

    /**
     * 计算当前时间离当天结束还有多少秒
     *
     * @return
     */
    public static int calcTodayEndSecond() {
        Calendar todayEnd = Calendar.getInstance();
        todayEnd.set(Calendar.HOUR_OF_DAY, 23);
        todayEnd.set(Calendar.MINUTE, 59);
        todayEnd.set(Calendar.SECOND, 59);
        return (int) ((todayEnd.getTime().getTime() - (System.currentTimeMillis())) / 1000);
    }

    /**
     * 计算当前时间离当天结束还有多少秒
     */
    public static int calcTodayEndMs() {
        return calcTodayEndSecond() * 1000;
    }
    /**
     * 计算今天还有多少秒结束
     *
     * @return
     * @description
     * @date 2016年1月12日
     */
    public static int calcTodayEndTime() {
        Calendar calendar = new GregorianCalendar();//子类实例化
        int h = calendar.get(Calendar.HOUR_OF_DAY);
        int m = calendar.get(Calendar.MINUTE);
        int s = calendar.get(Calendar.SECOND);
        return 24 * 60 * 60 - (h * 60 * 60 + m * 60 + s);
    }

}
